import json
from django import http
from django.contrib.auth import authenticate, login
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core import serializers
from django.core.exceptions import ObjectDoesNotExist
from django.db import DatabaseError
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View

from users.models import User
from bookinfo.models import BookInfo


# Create your views here.
# 展示管理员主界面
class Admin_Self(View):
    def get(self, request):
        return render(request, 'admin_self.html')


# 管理员登录
class Admin_login(View):
    def get(self, request):
        return render(request, 'admin_login.html')

    def post(self, request):
        admin_name = request.POST.get('admin')
        password = request.POST.get('password')
        # 校验
        if not all([admin_name, password]):
            return http.HttpResponseForbidden('缺少必传参数')
        superuser = authenticate(username=admin_name, password=password)
        # 认证用户
        if super is None:
            return render(request, 'admin_login.html', {'account_errmsg': '管理员认证失败'})
        login(request, superuser)
        is_staff = superuser.is_staff
        if is_staff != 1:
            return HttpResponse('<h1>管理员认证失败</h1>')
        next = request.GET.get('next')
        if next:
            response = redirect(next)
        else:
            response = redirect(reverse('administrator:admin_self'))
        response.set_cookie('username', superuser.username, max_age=3600 * 24 * 15)
        return response


# 展示管理员信息界面
class AdminInfo(View):
    def get(self, request):
        context = {
            'username': request.user.username,
            'email': request.user.email,
            'professional': request.user.professional,
        }
        return render(request, 'admin_info.html', context)


# 展示图书管理界面
class BookManage(View):
    def get(self, request):
        return render(request, 'book_manage.html')


# 展示用户管理界面
class UserManage(View):
    def get(self, request):
        return render(request, 'user_manage.html')


# 删除用户
class UserManageDelete(View):
    def get(self, request):
        user = User.objects.get(mobile=ID)
        user.is_deleted = True
        user.save()
        print(user.is_deleted)
        return HttpResponse('删除成功')


# 查找用户界面
class UserManageSearch(View):
    def get(self, request):
        return render(request, 'search_user.html')


# 查找单个用户
class UserManageSearchInfo(View):
    def get(self, request):
        p = request.GET.get('p')
        global ID
        try:
            user = User.objects.get(username=p)
            if user.is_deleted == True:
                return HttpResponse("<h1>该用户已被删除</h1>")
            else:
                ID = user.mobile
                context = {
                    'username': user.username,
                    'mobile': user.mobile,
                    'grade': user.grade,
                    'user_college': user.user_college,
                    'professional': user.professional,
                    'user_class': user.user_class,
                    'number': user.number,
                    'borrow_number': user.borrow_number,
                }
                return render(request, 'search_info.html', context)
        except ObjectDoesNotExist:
            return HttpResponse('<h1>未录入该用户！</h1>')


# 查询所有的用户基本信息
class AllUsers(View):
    def get(self, request):
        datas = User.objects.filter(is_deleted=False)
        return render(request, 'user_massageinfo.html', {'list': datas})


# 修改用户信息
class ChickUserMassage(View):
    def get(self, request):
        context = {
            "id": ID
        }
        return render(request, 'chick_usermassage.html', context)

    def post(self, request):
        print(ID)
        user = User.objects.get(mobile=ID)
        username = request.POST.get('username')
        user.username = username
        grade = request.POST.get('grade')
        user.grade = grade
        user_college = request.POST.get('user_college')  # 所属学院
        user.user_college = user_college
        # user_class = request.POST.get('user_class')  # 班级
        professional = request.POST.get('professional')  # 专业
        user.professional = professional
        print(username, grade, user_college, professional)
        # if not all([username, grade, user_college, professional]):
        #     return HttpResponse("<h1>缺少必要参数</h1>")
        # else:
        user.save()
        return HttpResponse('success')


# 查询所有图书
class SearchBook(View):
    def get(self, request):
        datas = BookInfo.objects.all()
        return render(request, 'search_book.html', {'list': datas})


# 查询单个图书界面
class SearchABook(View):
    def get(self, request):
        return render(request, 'search_abook.html')


# 测试模块
class Test(View):
    def get(self, request):
        return render(request, 'test.html')

    def post(self, request):
        '''登录校验视图'''
        # 浏览器提交的信息就保存在request里面
        # request.POST保存的是POST提交的参数
        # request.GET保存的是GET提交的参数
        # 1.获取提交的用户名和密码
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 2.进行登录校验
        # 实际开发的时候，用户名和密码保存在数据库中
        # 模拟
        return HttpResponse(username, password)
        # 3.返回应答


# 添加图书界面
class AddBook(View):
    def get(self, request):
        return render(request, 'add_book.html')

    def post(self, request):
        # 接受前端发送的信息
        name = request.POST.get('name')
        id = request.POST.get('id')
        ISBN = request.POST.get('ISBN')
        type = request.POST.get('type')
        author = request.POST.get('author')
        type_num = request.POST.get('type_num')
        pub_hou = request.POST.get('pub_hou')
        pub_date = request.POST.get('pub_date')
        edition = request.POST.get('edition')
        serial_num = request.POST.get('serial_num')
        context = {
            'name': name,
            'id': id,
            'ISBN': ISBN,
            'type': type,
            'author': author,
            'type_num': type_num,
            'pub_hou': pub_hou,
            'pub_date': pub_date,
            'edition': edition,
            'serial_num': serial_num,
        }
        print(context)
        # 验证信息
        # 1,验证信息是否完全（书名，图书编号，ISBN，类型，作者，类型编号，出版社，出版日期，版次，书架编号）
        if not all([name, id, ISBN, type, author, type_num, pub_hou, pub_date, edition, serial_num]):
            return HttpResponse("<h1>缺少必传的值</h1>")
        # 2,验证图书编号是否重复，如果重复返回<h1>注册失败，该图书编号已重复</h1>
        # 添加到数据库中
        try:
            BookInfo.objects.create(name=name, id=id, ISBN=ISBN, type=type, author=author,
                                    type_num=type_num, pub_hou=pub_hou, pub_date=pub_date,
                                    edition=edition, serial_num=serial_num)
        except DatabaseError:
            return HttpResponse('<h1>添加失败</h1>')
        # print(pub_date)
        # 返回重定向
        response = redirect(reverse('administrator:book_manage'))
        return response

# 查询单本图书
